import { Loading } from 'element-ui';
import config from 'js/config';
import popup from 'lib/popup/popup'
class util {
    constructor() {
        // userAgent
        this.win = window.top;
        this.UA = navigator.userAgent;
        this.isPC = this.UA.indexOf('Windows NT') > -1;
        this.isAndroid = this.UA.indexOf('Android') > -1;
        this.isIos = this.UA.indexOf('Mac OS X') > -1;
        this.isIphone = this.UA.indexOf('iPhone;') > -1;
        this.isIpad = this.UA.indexOf('iPad;') > -1;
        this.isIE7 = this.UA.indexOf('MSIE 7.0;') > -1;
        this.isIE8 = this.UA.indexOf('MSIE 8.0;') > -1;
        this.isIE9 = this.UA.indexOf('MSIE 9.0;') > -1;
        this.isIE10 = this.UA.indexOf('MSIE 10.0;') > -1;
        this.isIE11 = this.UA.indexOf('Trident') > -1;
        // loading
        this.loading = null;
        this.loadingcount = 0;
    }
    /*封装的ajax函数
	*type           	类型  get|post
	*url            	api地址
    *data           	请求的json数据
    *async              异步/同步
	*timeout			是否有请求超时
	*complete       	ajax完成后执行（失败成功后都会执行）
	*beforeSend        	请求发送前执行
	*success        	成功之后执行
	*error          	失败之后执行
	*goingError     	是否执行自定义error回调
	*timeout        	ajax超时时间
	*isGoingLogin   	是否跳转到登录界面
	*isShowLoading  	ajax执行是否显示遮罩
    */
    ajax(json) {
        if (!json.url) {
            console.warn('please inner your url');
            return;
        }
        if (json.async && typeof (json.async) !== 'boolean') {
            console.warn('async must be boolean');
            return;
        }
        if (json.timeout && typeof (json.timeout) !== 'number') {
            console.warn('timeout must be number');
            return;
        }
        let This = this,
            timer = null,
            noerror = true;
        let option = {
            isShowLoading: json.isShowLoading || true,
        }
        if (option.isShowLoading) {
            this.showLoading();
        }
        let conf = {
            type: json.type || 'post',
            url: json.url,
            data: json.data || {},
            async: json.async || true,
            timeout: json.timeout || config.ajaxtimeout,
            beforeSend(xhr) {
                json.beforeSend && json.beforeSend(xhr)
            },
            success(data) {
                if (typeof (data) == 'string') {
                    This.success(JSON.parse(data), json);
                } else {
                    This.success(data, json);
                }
            },
            error(xhr) {
                noerror && This.error(xhr, json)
            },
            complete(xhr) {
                --This.loadingcout;
                timer && clearTimeout(timer);
                if (This.loadingcount === 0) {
                    This.hideLoading();
                }
            }
        }
        if (conf.timeout !== 0) {
            timer = setTimeout(() => {
                if (option.isShowLoading) {
                    this.hideLoading();
                }
                noerror = false;
                conf.async && popup.alert({title:'您的网络太慢了哦,请刷新重试!'})
            }, conf.timeout);
        }
        ++this.loadingcout;//执行计数
        return $.ajax(conf)
    };

    //file 文件上传
    fileAJAX(json) {
        let This = this,
            timer = null,
            noerror = true;
        let option = {
            isShowLoading: json.isShowLoading || false,
        }
        if (option.isShowLoading) {
            this.showLoading();
        }
        let conf = {
            type: json.type || 'post',
            url: json.url,
            data: json.data || {},
            async: json.async || true,
            timeout: typeof (json.timeout) === 'number' ? json.timeout : config.ajaxtimeout,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            datatype: "json",
            cache: false,
            contentType: false,
            processData: false,
            beforeSend(xhr) {
                json.beforeSend && json.beforeSend(xhr)
            },
            success(data) {
                if (typeof (data) == 'string') {
                    This.success(JSON.parse(data), json);
                } else {
                    This.success(data, json);
                }
            },
            error(xhr) {
                noerror && This.error(xhr, json)
            },
            complete(xhr) {
                --This.loadingcout;
                timer && clearTimeout(timer);
                if (This.loadingcount === 0) {
                    This.hideLoading();
                }
            },
            xhr() {
                var xhr = jQuery.ajaxSettings.xhr();
                xhr.upload.onprogress = function (ev) {
                    console.log(ev)
                    if (ev.lengthComputable) {
                        var percent = 100 * ev.loaded / ev.total;
                        console.log(percent)
                        json.xhr && json.xhr(percent)
                    }
                }
                return xhr;
            },
        }
        console.log(json.timeout)
        console.log(conf.timeout)
        if (conf.timeout !== 0) {
            timer = setTimeout(() => {
                if (option.isShowLoading) {
                    this.hideLoading();
                }
                noerror = false;
                conf.async && popup.alert({ title: '您的网络太慢了哦,请刷新重试!' })
            }, conf.timeout);
        }
        ++this.loadingcout;//执行计数
        return $.ajax(conf)
    };

    //fileXHR 文件xhr上传
    fileXHR(json){
        if (!json.url) {
            console.warn('please inner your url');
            return;
        }
        if (!json.file) {
            console.warn('please inner your file');
            return;
        }
        var conf = {
            filename:json.filename || 'file',
            data:json.data || {},
        }
        // XMLHttpRequest 对象
        var xhr = new XMLHttpRequest();
        xhr.open("post", json.url, true);

        // FormData 对象
        var form = new FormData();
        // 文件对象
        form.append(conf.filename, json.file);
        // 其他参数
        for (var n in conf.data){
            form.append(n, conf.data[n]);
        }
        //上传进度
        xhr.upload.onprogress = function (ev) {
            console.log(ev)
            if (ev.lengthComputable) {
                var percent = 100 * ev.loaded / ev.total;
                console.log(percent)
                json.xhr && json.xhr(percent)
            }
        }
        //回调
        //异步接受响应
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    var data = JSON.parse(xhr.responseText);
                    var code = data.code - 0;
                    //实际操作
                    if (code == 1003) {
                        popup.alert({
                            title: '用户未登陆,请登录!',
                            yes: () => {
                                location.href = config.loginUrl
                            }
                        });
                    } else {
                        switch (code) {
                            case 1000:
                                json.success && json.success(data);
                                break;
                            default:
                                if (json.goingError) {
                                    //走error回调
                                    json.error && json.error(data);
                                } else {
                                    //直接弹出错误信息
                                    popup.alert({ title: data.desc });
                                };
                        }
                    };
                }
            }
        }
        xhr.send(form);
    }

    /*FormData 上传文件函数
	filename : string  input name 属性
	onlyOne : boolean   是否只上传一个文件
	data : Object      ajax上次的data数据
	url ：string      api地址
	checktype: array     默认['png','jpg'，'gif']
	nohideloading : boolean  	ajax执行完成之后是否隐藏遮罩
	timeout : number        	ajax超时时间
	goingError : boolean     	是否执行自定义error回调
	isGoingLogin : boolean   	是否跳转到登录界面
	success : function   成功之后的回调函数
	complete : function       	ajax完成后执行（失败成功后都会执行）
	error : function          	失败之后执行
	*/
    cerateFileFormData(json) {
        var This = this;
        var checktype = json.checktype || ['jpg', 'png', 'gif'];
        var filename = json.filename ? json.filename : 'filename'
        var html = '<div id="createFileHtml" class="hidden">';
        html += '<form enctype="multipart/form-data" id="uploadForm">';
        html += '<input type="file" name="' + filename + '" id="expInputFile" ';
        if (!json.onlyOne) { html += ' multiple="multiple"' }
        html += '></div></form>';
        if ($('#createFileHtml').length) {
            $('#createFileHtml').remove();
        }
        $('body').append(html);
        $('#expInputFile').click();
        $('#expInputFile').one('change', function () {
            // 检查文件类型
            if(checktype.length>0){
                var files = $('#expInputFile')[0].files;
                for (var i = 0; i < files.length; i++) {
                    var begin = false;
                    for (var k = 0; k < checktype.length; k++) {
                        var checked = new RegExp("\." + checktype[k] + "$").test(files[i]['name'].toLowerCase());
                        if (!checked) { continue; }
                        begin = checked;
                    }
                    if (!begin) {
                        popup.alert({ title: '请上传正确的文件类型！' }); return false;
                    };
                }
            }
            // 执行ajax
            var formData = new FormData($("#uploadForm")[0]);
            if (json.data) {
                for (var i in json.data) {
                    formData.append(i, json.data[i]);
                };
            };
            This.fileAJAX({
                url: json.url,
                data: formData,
                isShowLoading: json.isShowLoading || false,
                goingError: json.goingError || false,
                timeout: typeof (json.timeout) === 'number' ? json.timeout : config.ajaxtimeout,
                beforeSend: function (xhr) {
                    json.beforeSend && json.beforeSend(xhr);
                },
                success: function (data) {
                    $('#createFileHtml').remove();
                    json.success && json.success(data);
                },
                error: function (data) {
                    $('#createFileHtml').remove();
                    json.error && json.error(data, json);
                },
                complete: function (data) {
                    json.complete && json.complete(data);
                },
                xhr: function (data) {
                    json.xhr && json.xhr(data)
                }
            });
        });
    }

    success(data, json) {
        let code = data.code - 0;
        if (!json.isGoingLogin && code == 1003) {
            popup.alert({
                title:'用户未登陆,请登录!',
                yes:()=>{
                    location.href = config.loginUrl
                }
            });
        } else {
            switch (code) {
                case 1000:
                    json.success && json.success(data);
                    break;
                default:
                    if (json.goingError) {
                        //走error回调
                        json.error && json.error(data);
                    } else {
                        //直接弹出错误信息
                        popup.alert({title:data.desc});
                    };
            }
        };
    };
    error(XMLHttpRequest, json) {
        if (json.code) {
            json.error(JSON.parse(XMLHttpRequest.responseText));
        } else {
            switch (XMLHttpRequest.status) {
                case 401:
                    popup.alert({title:XMLHttpRequest.status})
                    break;
                case 400:
                    popup.alert({title:XMLHttpRequest.status})
                    break;
                case 404:
                    popup.alert({title:XMLHttpRequest.status})
                    break;
                case 500: case 502:
                    popup.alert({title:XMLHttpRequest.status})
                    break;
            }
        }
    };


    // loading
    showLoading() {
        this.loading = Loading.service({
            fullscreen: true
        });
    };
    hideLoading() {
        this.loading && this.loading.close();
    };

    /*根据参数生成常用的正则表达式
    *string    type 生成的正则表达式类型
    *array     numArr 生成正则的条件数组 例如:[6,16] 也可省略
    */
    regCombination(type, numArr) {
        var reg = "";
        switch (type) {
            case "*":     //"*":"不能为空！"   
                if (numArr) {
                    reg = new RegExp("^[\\w\\W]{" + numArr[0] + "," + numArr[1] + "}$");
                } else {
                    reg = new RegExp("^[\\w\\W]+$");
                }
                break;
            case "n":    //"number":"请填写数字！
                if (numArr) {
                    reg = new RegExp("^\\d{" + numArr[0] + "," + numArr[1] + "}$");
                } else {
                    reg = new RegExp("^\\d+$");
                }
                break;
            case "s":  //"s":"不能输入特殊字符！"   
                if (numArr) {
                    reg = new RegExp("^[\\u4E00-\\u9FA5\\uf900-\\ufa2d\\w\\.\\s]{" + numArr[0] + "," + numArr[1] + "}$");
                } else {
                    reg = new RegExp("^[\\u4E00-\\u9FA5\\uf900-\\ufa2d\\w\\.\\s]+$");
                }
                break;
            case "c":  //"z":"中文验证" 
                reg = new RegExp("^[\\u4E00-\\u9FA5\\uf900-\\ufa2d]{" + numArr[0] + "," + numArr[1] + "}$");
                break;
            case "p":    //"p":"邮政编码！
                reg = new RegExp("^[0-9]{6}$");
                break;
            case "m":    //"m":"写手机号码！"
                reg = new RegExp("^13[0-9]{9}$|14[0-9]{9}$|15[0-9]{9}$|17[0-9]{9}$|18[0-9]{9}$");
                break;
            case "e":   //"e":"邮箱地址格式
                reg = new RegExp("^\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
                break;
            case "id":   //"id":验证身份证
                reg = new RegExp("^\\d{17}[\\dXx]|\\d{14}[\\dXx]$");
                break;
            case "money": //钱
                reg = new RegExp("^[\\d\\.]+$");
                break;
            case "url":   //"url":"网址"
                reg = new RegExp("^(\\w+:\\/\\/)?\\w+(\\.\\w+)+.*$");
                break;
            case "u":    //
                reg = new RegExp("^[A-Z\\d]+$");
                break;
        }
        return reg;
    }

    //设置cookie
    setCookie(cname, cvalue, exdays) {
        var d = new Date();
        d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        document.cookie = cname + "=" + cvalue + "; " + expires;
    }
    //获取cookie
    getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1);
            if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
        }
        return "";
    }
    //清除cookie  
    clearCookie(name) {
        this.setCookie(name, "", -1);
    } 

    /*获取 storage 缓存数据
	* type  类型   local：localStorage   session：sessionStorage
	* name  缓存数据name名
	*/
    getStorage(type, name) {
        var type = type || 'local';
        if (type == 'local') {
            var result = localStorage.getItem(name) ? localStorage.getItem(name) : "";
        } else if (type == 'session') {
            var result = sessionStorage.getItem(name) ? sessionStorage.getItem(name) : "";
        }
        return result;
    }

    /*设置 storage 缓存数据
    *type  类型   local：localStorage   session：sessionStorage
    *name  缓存数据name名
    *content  缓存的数据内容
    */
    setStorage(type, name, content) {
        var type = type || 'local';
        var data = content;
        if (typeof (data) == 'object') { data = JSON.stringify(content) };
        if (type == 'local') {
            localStorage.setItem(name, data);
        } else if (type == 'session') {
            sessionStorage.setItem(name, data);
        }
    }

    //秒数换算成时间函数 得到00:00:00 格式
    formatSeconds(value) {
        var second = parseInt(value);// 秒
        var minute = 0;// 分
        var hour = 0;// 小时
        if (second > 60) {
            minute = parseInt(second / 60);
            second = parseInt(second % 60);
            if (minute > 60) {
                hour = parseInt(minute / 60);
                minute = parseInt(minute % 60);
            }
        }
        var result = this.getZero(minute) + ':' + this.getZero(parseInt(second));
        if (minute > 0) {
            result = this.getZero(parseInt(minute)) + ":" + this.getZero(parseInt(second));
        }
        if (hour > 0) {
            result = this.getZero(parseInt(hour)) + ':' + this.getZero(parseInt(minute)) + ":" + this.getZero(parseInt(second));
        }
        return result;
    }
    /*判断时间前面是否加0*/
    getZero(num) {
        if (num < 10) {
            return '0' + num;
        } else {
            return num;
        }
    }

    /* 短信定时器
      nowTime vue.js 初始数据  当前时间
      getMsgText vue.js 初始数据  当前的提示文字
    */
    getMsgTime(This, msgText) {
        var nowTime = config.msgTime;
        return new Promise((resolve,reject)=>{
            var timer = setInterval(() => {
                console.log(nowTime)
                nowTime--;
                This[msgText] = nowTime + ' S后重发';
                //时间走完时执行
                if (nowTime <= 0) {
                    clearInterval(timer);
                    This[msgText] = "重新获取";
                    resolve();
                }
            }, 1000);
        })
    }

    /*
*对象转化成参数serialize
*/
    serialize(url, obj) {
        let str = url.indexOf('?') > -1 ? '&' : '?'
        for (let n in obj) {
            str += `${n}=${obj[n]}&`
        }
        return url + str.slice(0, -1)
    }

    //新建iframe 并赋src   文件下载时用得到
    interIosForIframe(filename,src, isEncode) {
        var a = document.createElement('a');
        a.href = src;
        if (filename)a.download = filename;
        document.body.append(a);
        a.click();
        a.remove();
    };

    /*---------数据操作start-------------*/
        /*传入一个对象，返回该对象的值不为空的所有参数，并返回一个对象
         obj   object    传入的对象
        */
        objDislodge(obj, noclone) {
            var objData = noclone ? obj : JSON.parse(JSON.stringify(obj));
            for (var n in objData) {
                if (objData[n] === null || objData[n] === '') {
                    delete objData[n]
                }
            }
            return objData;
        }

        /*传入一个json对象，返回该对象的值不为空的所有参数，并返回一个对象
         json   object    传入的对象
        */
        jsonDislodge(json) {
            var objData = JSON.parse(JSON.stringify(obj));
            objData.forEach((item, index) => {
                for (let n in item) {
                    if (item[n] == null || item[n] == '') {
                        delete item[n]
                    }
                }
            })
            return objData;
        }

        /*将json里面某个参数的参数名替换成另外一个参数名
         name1:初始参数名
         name2:替换后参数名
        */
        jsonNameReplace(json, name1, name2) {
            var json = JSON.parse(JSON.stringify(json));
            json.forEach((item, index) => {
                item[name2] = item[name1];
                delete item[name1];
            })
            return json;
        }

        /*
         除掉对象里面的某些参数
        */
        delObjByArr(obj, arr) {
            var obj = obj;
            arr.forEach((item, index) => {
                delete obj[item]
            })
            return obj;
        }

        /*
         传入一个json数组和所需要的参数集，返回一个全新的json数组
        */
        getNewJson(json, arr) {
            var array = [];
            json.forEach((item, index) => {
                var obj = {};
                for (var i = 0, len = arr.length; i < len; i++) {
                    for (var n in item) {
                        if (arr[i] == n) {
                            obj[arr[i]] = item[n];
                        }
                    }
                }
                array.push(obj);
            })
            return array;
        }

        /*
         传入一个对象和所需要的参数集，返回一个全新的对象
        */
        getNewObj(obj, arr) {
            var object = {};
            for (var n in obj) {
                for (var i = 0, len = arr.length; i < len; i++) {
                    if (n == arr[i]) {
                        object[n] = obj[n]
                    }
                }
            }
            return object;
        }
    /*向json数组里面添加一个字段
arr 需要push的arr json数组
pushps:[{key:'name',val:125}]  第一层push的数据
deeplevel  是否有更深栏目需要push 有就传下面的参数
listkey    需要push的二层数据key名字
pushcs:[{key:'name',val:125}] 第二层push的数据
*/
    pushKeVaInArr(json) {
        for (var i = 0, len = json.arr.length; i < len; i++) {
            for (var k = 0; k < json.pushps.length; k++) {
                json.arr[i][json.pushps[k]['key']] = json.pushps[k]['val']
            }
            if (json.deeplevel) {
                for (var j = 0, lenj = json.arr[i][json.listkey].length; j < lenj; j++) {
                    for (var o = 0; o < json.pushcs.length; o++) {
                        json.arr[i][json.listkey][j][json.pushcs[o]['key']] = json.pushcs[o]['val']
                    };
                }
            }
        }
        return json.arr;
    }
    /*检测某值在数组中是否存在 并返回存在的索引值
arr         数组集合（一维json数组）
value       json的key值
checkKey    检测的key值
*/
    isInArrayAndIndex(arr, value, checkKey) {
        var result = {
            isin: false,
            index: 0
        };
        for (var i = 0, len = arr.length; i < len; i++) {
            if (value == arr[i][checkKey]) {
                result.isin = true;
                result.index = i;
            };
        };
        return result;
    }
    /*获得数组中某个key值的集合
arr  数组集合（一维json数组）
key  string
*/
    getArrsItems(arr, key) {
        var str = "";
        for (var i = 0; i < arr.length; i++) {
            str += arr[i][key] + ',';
        }
        return str.slice(0, -1);
    }
    /*---------数据操作end-------------*/
}
window['util'] = new util();